package com.xhtt.modules.cfg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.CopyUtils;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.cfg.dao.CfgPumpInfoMapper;
import com.xhtt.modules.cfg.entity.*;
import com.xhtt.modules.cfg.model.RelateObj;
import com.xhtt.modules.cfg.schedule.PumpLog;
import com.xhtt.modules.cfg.service.CfgPumpInfoService;
import com.xhtt.modules.cfg.service.CfgPumpLogService;
import com.xhtt.modules.cfg.service.CfgPumpProductService;
import com.xhtt.modules.cfg.service.CfgPumpRelateService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 泵库 服务实现类
 * </p>
 *
 * @author feipc
 * @since 2019-02-20
 */
@Service
public class CfgPumpInfoServiceImpl extends ServiceImpl<CfgPumpInfoMapper, CfgPumpInfo> implements CfgPumpInfoService {
    @Autowired
    private CfgPumpRelateService pumpRelateService;
    @Autowired
    private CfgPumpProductService cfgPumpProductService;
    @Autowired
    private CfgPumpLogService pumpLogService;

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<CfgPumpInfo> page = new Query<CfgPumpInfo>(params).getPage();
        List<CfgPumpInfo> list = baseMapper.queryPage(page, params);
        //连接点
//        for (CfgPumpInfo pumpInfo : list) {
//            List<CfgPumpRelate> pumpRelates = pumpRelateService.list(new LambdaQueryWrapper<CfgPumpRelate>().eq(CfgPumpRelate::getPumpId, pumpInfo.getId()));
//            List<CfgPumpRelate> guan = pumpRelates.stream().filter(cfgPumpRelate -> cfgPumpRelate.getType().intValue() == 1).collect(Collectors.toList());//罐
//            List<CfgPumpRelate> yingguan = pumpRelates.stream().filter(cfgPumpRelate -> cfgPumpRelate.getType().intValue() == 2).collect(Collectors.toList());//硬管
//            List<CfgPumpRelate> beng = pumpRelates.stream().filter(cfgPumpRelate -> cfgPumpRelate.getType().intValue() == 3).collect(Collectors.toList());//泵
//            List<CfgPumpRelate> matou = pumpRelates.stream().filter(cfgPumpRelate -> cfgPumpRelate.getType().intValue() == 4).collect(Collectors.toList());//码
//            pumpInfo.setRelateObject("待完善连接点 todo");
//        }

        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updatePump(CfgPumpInfo cfgPumpInfo) {
        int count = this.count(new LambdaQueryWrapper<CfgPumpInfo>().eq(CfgPumpInfo::getNumberNo, cfgPumpInfo.getNumberNo()).ne(CfgPumpInfo::getId, cfgPumpInfo.getId()).ne(CfgPumpInfo::getStatus, -1));
        if (count > 0) {
            throw new RRException("编号已存在");
        }
        CfgPumpInfo db = this.getById(cfgPumpInfo.getId());//取出对比 记日志
        this.updateById(cfgPumpInfo);
        Integer pumpId = cfgPumpInfo.getId();
        CfgPumpProduct pumpProduct = cfgPumpInfo.getPumpProduct();

        CfgPumpProduct dbproduct = cfgPumpProductService.getOne(new LambdaQueryWrapper<CfgPumpProduct>().eq(CfgPumpProduct::getPumpId, pumpId));
        CfgPumpProduct dbproduct2 = new CfgPumpProduct();
        CopyUtils.copyProperties(dbproduct, dbproduct2);
        List<CfgPumpProduct> dbProducts = new ArrayList<>();
        if (null != dbproduct2) {
            dbProducts.add(dbproduct2);
        }
        if (null != pumpProduct) {
            if (null == dbproduct) {
                pumpProduct.setType(1);
                pumpProduct.setPumpId(pumpId);
                cfgPumpProductService.save(pumpProduct);
            } else {
                dbproduct.setProductId(pumpProduct.getProductId());
                dbproduct.setName(pumpProduct.getName());
                cfgPumpProductService.updateById(dbproduct);
            }
        } else {
            if (null == dbproduct) {
                pumpProduct = new CfgPumpProduct();
                pumpProduct.setType(1);
                pumpProduct.setPumpId(pumpId);
                cfgPumpProductService.save(pumpProduct);
            } else {
                UpdateWrapper<CfgPumpProduct> uw = new UpdateWrapper<>();
                uw.set("product_id", null);
                uw.set("name", null);
                uw.eq("id", dbproduct.getId());
                cfgPumpProductService.update(new CfgPumpProduct(), uw);
            }
        }

        taskExecutor.submit(new PumpLog(cfgPumpInfo, db, dbProducts, MDC.get("deptUser")));
    }

    @Override
    @Transactional
    public void addPump(CfgPumpInfo cfgPumpInfo) {
        String numberNo = cfgPumpInfo.getNumberNo();
        int count = this.count(new LambdaQueryWrapper<CfgPumpInfo>().eq(CfgPumpInfo::getNumberNo, numberNo).ne(CfgPumpInfo::getStatus, -1));
        if (count > 0) {
            throw new RRException("编号已存在");
        }
        this.save(cfgPumpInfo);
        CfgPumpProduct pumpProduct = cfgPumpInfo.getPumpProduct();
        if (null == pumpProduct) {
            pumpProduct = new CfgPumpProduct();
        }
        pumpProduct.setPumpId(cfgPumpInfo.getId());
        pumpProduct.setType(1);//默认就是常用产品
        cfgPumpProductService.save(pumpProduct);
    }

    @Override
    @Transactional
    public void updateRelate(List<CfgPumpRelate> pumpRelateList) {
        Integer pumpId = pumpRelateList.get(0).getPumpId();
        //全删全增
        pumpRelateService.remove(new LambdaQueryWrapper<CfgPumpRelate>().eq(CfgPumpRelate::getPumpId, pumpId));
        pumpRelateService.saveBatch(pumpRelateList);
    }

    @Override
    public List<CfgPumpRelate> getRelateObject(Integer pumpId) {
        List<CfgPumpRelate> list = pumpRelateService.list(new LambdaQueryWrapper<CfgPumpRelate>().eq(CfgPumpRelate::getPumpId, pumpId));
        List<RelateObj> relateObjs;
        RelateObj ro;
        for (CfgPumpRelate re : list) {
            relateObjs = new ArrayList<>();
            ro = new RelateObj(re.getRelateId(), re.getName());
            relateObjs.add(ro);
            re.setSubRelates(relateObjs);
        }
        return list;
    }

    @Override
    @Transactional
    public void updateRelateObject(List<CfgPumpRelate> relates) {
        //全删全增
        Integer pumpId = relates.get(0).getPumpId();
        if (null == pumpId) {
            throw new RRException("参数有误");
        }
        pumpRelateService.remove(new LambdaQueryWrapper<CfgPumpRelate>().eq(CfgPumpRelate::getPumpId, pumpId));
        pumpRelateService.saveBatch(relates);
    }

    @Override
    public void updateUsed(List<Integer> upPumpIds, Integer productId, String productName) {
        baseMapper.updateUsed(upPumpIds);
        baseMapper.updateCurProduct(upPumpIds, productId, productName);
    }

    @Override
    public void flushProduct(List<Integer> pumpIdList) {
        baseMapper.flushProduct(pumpIdList);
    }

    @Override
    public void updateUnUsed(List<Integer> upPumpIds) {
        CfgPumpInfo pump = new CfgPumpInfo();
        pump.setUsed(0);
        this.update(pump, new LambdaQueryWrapper<CfgPumpInfo>().in(CfgPumpInfo::getId, upPumpIds));
    }

    @Override
    public PageUtils logList(Map<String, Object> params) {
        Page<CfgPumpLog> page = new Query<CfgPumpLog>(params).getPage();
        pumpLogService.page(page.setDesc("id"), new LambdaQueryWrapper<CfgPumpLog>().eq(CfgPumpLog::getPumpId, params.get("id")));
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateRfid(CfgPumpInfo cfgPumpInfo) {
        CfgPumpInfo old = this.getById(cfgPumpInfo.getId());
        if (StringUtils.isEmpty(cfgPumpInfo.getRfid())) {
            this.update(new CfgPumpInfo(), new UpdateWrapper<CfgPumpInfo>().set(CfgPumpInfo.RFID, "").eq(CfgPumpInfo.ID, cfgPumpInfo.getId()));
        } else {
            this.updateById(cfgPumpInfo);
        }
        if (!ObjectUtils.nullSafeEquals(cfgPumpInfo.getRfid(), old.getRfid())) {
            String rfidInfo = old.getRfid() + " → " + cfgPumpInfo.getRfid();
            CfgPumpLog log = new CfgPumpLog();
            log.setPumpId(cfgPumpInfo.getId());
            log.setDeptUser(MDC.get("deptUser"));
            log.setRfidInfo(rfidInfo);
            log.setComProductInfo("");
            pumpLogService.save(log);
        }
    }

}
